import 'package:Sayagh/Configs.dart';
import 'package:Sayagh/i18n/i18nLocale.dart';
import 'package:Sayagh/tablepress/Categories.dart';
import 'package:Sayagh/tablepress/csv.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';

class City {
  int id;
  int stateCode;
  int cityCode;
  int postCode;
  int isActive;
  String title;
  String fileName;
  String url;
  int hasSubTable;
  int hasCategoryColumn;
  int hasSubCategoryColumn;
  String description;
  City();
  City.fromMap(Map<String, dynamic> _city) {
    id = _city['id'];
    stateCode = _city['stateCode'];
    cityCode = _city['cityCode'];
    postCode = _city['postCode'];
    isActive = _city['isActive'];
    title = _city['title'];
    fileName = _city['fileName'];
    url = _city['url'];
    hasSubTable = _city['hasSubTable'];
    hasCategoryColumn = _city['hasCategoryColumn'];
    description = _city['description'];
  }
  City.fromList(List<dynamic> cityList) {
    isActive = int.parse(cityList.removeAt(0));
    title = cityList.removeAt(0);
    try {
      fileName = cityList.removeAt(0);
    } catch (e) {
      cityList.removeAt(0);
    }
    url = cityList.removeAt(0);
    description = cityList.removeAt(0);
    hasSubTable = int.parse(cityList.removeAt(0));
    hasCategoryColumn = int.parse(cityList.removeAt(0));
    hasSubCategoryColumn = int.parse(cityList.removeAt(0));
    stateCode = int.parse(cityList.removeAt(0));
    cityCode = int.parse(cityList.removeAt(0));
    postCode = int.parse(cityList.removeAt(0));
  }
  Map<String, dynamic> toMap() {
    Map<String, dynamic> _city = {
      "postCode": postCode,
      "stateCode": stateCode,
      "cityCode": cityCode,
      "isActive": isActive,
      "title": title,
      "url": url,
      "hasSubTable": hasSubTable,
      "hasCategoryColumn": hasCategoryColumn,
      "hasSubCategoryColumn": hasSubCategoryColumn,
    };
    if (id != null) _city['id'] = id;
    if (fileName != null) _city['fileName'] = fileName;
    if (description != null) _city['description'] = description;
    return _city;
  }
}

class CityProvide {
  Database db;

  Future open() async {
    db = await openDatabase(
      ourDatabase,
      version: 1,
      onOpen: (Database db) async {
        String sqlQuery = '''
    CREATE TABLE IF NOT EXISTS "$cityTableName" (
      "id"	INTEGER PRIMARY KEY AUTOINCREMENT,
      "stateCode" Integer,
      "cityCode" INTEGER NOT NULL,
      "postCode"	INTEGER NOT NULL UNIQUE,
      "isActive"	INTEGER DEFAULT 1,
      "title"	TEXT NOT NULL UNIQUE,
      "fileName"	TEXT,
      "url" TEXT default 'http://sayagh.asnafhormozgan.ir',
      "hasSubTable"	INTEGER NOT NULL DEFAULT 0,
      "hasCategoryColumn"	INTEGER NOT NULL DEFAULT 0,
      "hasSubCategoryColumn"	INTEGER NOT NULL DEFAULT 0,
      "description"	TEXT
    );
  ''';
        await db.execute(sqlQuery);
      },
    );
  }

  Future<City> insert(City city) async {
    city.id = await db.insert("$cityTableName", city.toMap());
    return city;
  }

  Future<City> getCity(int code, {bool byPostCode = true}) async {
    String column = "postCode";
    if (!byPostCode) column = "id";
    if (db == null || !db.isOpen) await open();
    List<Map> maps =
        await db.query(cityTableName, where: '$column = ?', whereArgs: [code]);
    if (maps.length > 0) return City.fromMap(maps.first);
    return null;
  }

  Future<int> delete(int code, {bool byPostCode = true}) async {
    String column = "postCode";
    if (!byPostCode) column = "id";
    return await db
        .delete(cityTableName, where: "$column = ?", whereArgs: [code]);
  }

  Future<int> update(City city, {bool byPostCode = true}) async {
    String column = byPostCode ? "postCode" : "id";
    int whereArg = byPostCode ? city.postCode : city.id;
    if (!db.isOpen) open();
    return await db.update(cityTableName, city.toMap(),
        where: "$column = ?", whereArgs: [whereArg]);
  }

  Future insertOrUpdate(City city, {bool byPostCode = true}) async {
    int whereArg = byPostCode ? city.postCode : city.id;
//    if (!db.isOpen) await open();
    final City _city = byPostCode
        ? await getCity(whereArg)
        : await getCity(whereArg, byPostCode: false);
    if (_city == null) return await insert(city);
    return byPostCode
        ? await update(city)
        : await update(city, byPostCode: false);
  }

  Future<List<City>> getAllShouldShow() async {
    bool wasOpen = false;
    if (db != null) wasOpen = db.isOpen;
    if (!wasOpen) await open();
    List<Map> _c =
        await db.query(cityTableName, where: "isActive > 0", orderBy: "id");
    List<City> c = [];
    _c.forEach((__c) {
      c.add(new City.fromMap(__c));
    });
//    print(c);
//    if (!wasOpen) close();
    return c;
  }

  Future close() async => await db.close();
}

Future updateDrawerCitiesDb() async {
  List<List> citiessList = await csv(sayaghWebsite, "cities", "شهرها");
  citiessList = citiessList[1];
  City city;
  CityProvide cityProvide = new CityProvide();
//  await cityProvide.open();
  for (int i = 0; i < citiessList.length; i++) {
    if (citiessList[i].length < 9) continue;
    city = null;
    city = City.fromList(citiessList[i]);
    await cityProvide.insertOrUpdate(city);
  }
//  await cityProvide.close();

  print("done");
}

class CitiesCards extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    String citiessUrl = "$cities";
    Future<List<List>> citiessList = csv(sayaghWebsite, "cities", "شهرها");

    return Scaffold(
      appBar: AppBar(
        title: asnafHeader,
      ),
//      appBar: AppBar(title: Text(i18nLocale[ourLocale]['citiess']),),
      body: FutureBuilder(
        future: citiessList,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.data == null) {
            return Card(
              child: Text(i18nLocale[ourLocale]['reciving']),
            );
          } else {
            return ListView.builder(
                itemCount: snapshot.data[1].length - 1,
                itemBuilder: (BuildContext context, int index) {
                  List<String> cities = snapshot.data[1][index];

                  Color color = Colors.greenAccent;
                  if (index % 2 == 0) {
                    color = Colors.lightGreen;
                  }

                  return Card(
                      color: color,
                      child: InkWell(
                        child: Text(
                          cities[1],
                          textDirection: TextDirection.rtl,
                          textAlign: TextAlign.center,
                        ),
                        onTap: () => Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => Categories(
                                    cities[3], cities[2], cities[1]))),
                      ));
                });
          }
        },
      ),
    );
  }
}
